<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of file
 *
 * @author b4by
 */
class file extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('model_file');
		
		$oldImgs = $this->model_file->get_list(array(
			'where'	=> array(
				'status'	=> 0,
				'time <'	=> now()-2*60*60
			)
		));
		foreach($oldImgs as $img){
			$this->delImage($img->file_name);
			$this->delImage($img->thumb_name);
			$this->model_file->del($img->id);
		}
	}

	public function upload() {
		$config = array();
		$config['encrypt_name'] = $this->siteConfig->image_encrypt_name == 1;
		$config['upload_path'] = $this->siteConfig->image_upload_path;
		$config['allowed_types'] = $this->siteConfig->image_types;
		$config['max_size'] = $this->siteConfig->image_max_size;
		$config['max_width'] = $this->siteConfig->image_max_width;
		$config['max_height'] = $this->siteConfig->image_max_height;

		$this->load->library('upload', $config);
		if ($this->upload->do_upload('file')) {
			$upload = $this->upload->data();
			$path = $config['upload_path'] . '/' . $upload['file_name'];

			$resize_config = array(
				'source_image' => $upload['full_path'],
				'maintain_ratio' => TRUE,
				'width' => $this->siteConfig->image_width,
				'height' => $this->siteConfig->image_height,
			);
			$size = getimagesize($upload['full_path']);
			if($size[0]>$this->siteConfig->image_width){
				$this->load->library('image_lib', $resize_config);
				$this->image_lib->resize();
			}
			$resize_config['height'] = $this->siteConfig->thumb_height;
			$resize_config['width'] = $this->siteConfig->thumb_width;
			$resize_config['create_thumb'] = TRUE;
			$this->load->library('image_lib', $resize_config, 'image_lib1');
			$this->image_lib1->resize();

			$thumb = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb$2', $path);

			$id = $this->model_file->create(array(
				'file_name' => $path,
				'orig_name' => $upload['orig_name'],
				'thumb_name'	=> $thumb,
				'time' => now(),
				'status' => 0,
					));
			echo json_encode(array(
				'state' => 'success',
				'id' => $id,
				'image' => image_url($path),
				'thumb'	=> image_url($thumb),
			));
		} else {
			echo json_encode(array(
				'state' => 'error',
				'message' => preg_replace('/<p>([^<]+)<\/p>/i', '$1', $this->upload->display_errors()),
			));
		}
	}

}

?>
